package ideamaps.manager;


import ideamaps.domain.Friend;
import ideamaps.domain.Request;
import ideamaps.domain.User;

import java.util.Date;
import java.util.List;

import com.sun.corba.se.impl.orbutil.GetPropertyAction;
import com.taillive.core.dao.HibernateEntityDao;
import com.taillive.core.dao.support.Page;

public class FriendManager extends HibernateEntityDao<Friend> {
	
	
	private UserManager userManager;
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public Page getPageByUserId(long userId,int pageNo,int pageSize) {
		return pagedQuery("select f from Friend f where f.user.id=?", pageNo, pageSize,userId);
	}
	
	public void create(Friend Friend) {
		save(Friend);
	}
	
	public void update(Friend Friend) {
		save(Friend);
	}
	
	public void delete(Long id) {
		removeById(id);
	}
	
	public void delete(Long ids[]) {
		for(Long id:ids){
			delete(id);
		}
	}
	
	public long countRequests(String username) {
		return count("select count(req) from Request req where req.user.username=?", username);
	}
	
	public List<Request> getRequestsByUsername(String username) {
		return find("select req from Request req where req.user.username=?", username);
	}
	
	public void addFriend(String username,String requestUsername,String message) {
		Request request = new Request();
		request.setCreated(new Date());
		request.setUser(userManager.getByUsername(username));
		request.setRequestUser(userManager.getByUsername(requestUsername));
		request.setMessage(message);
		
		save(request);
	}
	
	public Request getRequestByUsernameAndRequestUsername(String username,String requestUsername) {
		return getUnique("select req from Request req where req.user.username=? and req.requestUser.username=?", username,requestUsername);
	}
	
	public Friend getFriendByUsernameAndFriendUsername(String username,String friendUsername) {
		return getUnique("select f from Friend f where f.user.username=? and f.friend.username=?", username, friendUsername);
	}
	
	public void ignoreRequest(long requestId) {
		Request req = get(Request.class,requestId);
		if(req!=null)
			remove(req);
	}
	
	public void approveRequest(long requestId) {
		Request req = get(Request.class,requestId);
		
		if(req!=null){
			Friend f =getFriendByUsernameAndFriendUsername(req.getRequestUser().getUsername(), req.getUser().getUsername());
			if(f==null) {
			Date created = new Date();

			Friend friend1 = new Friend();
			friend1.setCreated(created);
			friend1.setUser(req.getUser());
			friend1.setFriend(req.getRequestUser());
			
			Friend friend2 = new Friend();
			friend2.setCreated(created);
			friend2.setUser(req.getRequestUser());
			friend2.setFriend(req.getUser());
			
			save(friend1);
			save(friend2);
			
			}
			remove(req);
		}
	}

}
